package com.jiefutong.zyt;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiefutong.zyt.utils.PrefsUtil;
import com.just.agentweb.AbsAgentWebSettings;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.IAgentWebSettings;
import com.just.agentweb.WebListenerManager;
import com.just.agentweb.download.DefaultDownloadImpl;
import com.just.agentweb.download.DownloadListenerAdapter;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class WebActivity extends AutoLayoutActivity {
    private ImageButton backBtn;
    private TextView titleText;
   // private WebView webView;
    private String url;
    private String titleStr;
    private String tokens;
    private RelativeLayout mRlContent;
    private AgentWeb mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
       // url=getIntent().getStringExtra("url");
       url="https://www.baidu.com/";
        titleStr=getIntent().getStringExtra("title");
        tokens= PrefsUtil.getString(getApplicationContext(), "token","");
        initView();
    }

    private void initView() {
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText("哈哈哈");
        backBtn = (ImageButton) findViewById(R.id.backBtn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


       mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mRlContent, new RelativeLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .setAgentWebWebSettings(getSettings())
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready()
                .go(url);

      /*  webView=findViewById(R.id.webView);
        //设置是否支持缩放
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        //设置是否显示缩放按钮
        webView.getSettings().setDisplayZoomControls(true);
        //设置WebView是否允许执行JavaScript脚本，默认false，不允许
        webView.getSettings().setJavaScriptEnabled(true);
//设置自适应屏幕宽度
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        Map<String, String> heads = new HashMap<>();
        heads.put("Accept", "application/json");
        heads.put("Authorization", tokens);
        //System.out.println("-------token:"+tokens);
        webView.loadUrl(url, heads);*/

    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (tokens != null && !TextUtils.isEmpty(tokens)) {
                Map<String, String> heads = new HashMap<>();
                heads.put("Accept", "application/json");
                heads.put("Authorization", tokens);
                view.loadUrl(url, heads);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    };


    /**
     * @return IAgentWebSettings
     */
    public IAgentWebSettings getSettings() {
        return new AbsAgentWebSettings() {
            private AgentWeb mAgentWeb;

            @Override
            protected void bindAgentWebSupport(AgentWeb agentWeb) {
                this.mAgentWeb = agentWeb;
            }

            /**
             * 如果你需要监听下载结果，请自定义 AgentWebSetting ， New 出 DefaultDownloadImpl，传入DownloadListenerAdapter
             * 实现进度或者结果监听，例如下面这个例子，如果你不需要监听进度，或者下载结果，下面 setDownloader 的例子可以忽略。
             * @param webView
             * @param downloadListener
             * @return WebListenerManager
             */
            @Override
            public WebListenerManager setDownloader(WebView webView, DownloadListener downloadListener) {
                return super.setDownloader(webView,
                        DefaultDownloadImpl
                                .create((Activity) webView.getContext(),
                                        webView,
                                        adapter,
                                        adapter,
                                        this.mAgentWeb.getPermissionInterceptor()));
            }
        };
    }

    private DownloadListenerAdapter adapter = new DownloadListenerAdapter() {
        @Override
        public boolean onResult(String path, String url, Throwable throwable) {
            if (null == throwable) {

            } else {
                if (null == throwable) {
                    //showToast("下载失败,请重试");
                } else {
                    install(path);
                }
            }
            return false;
        }

        @Override
        public void onProgress(String url, long downloaded, long length, long usedTime) {
            super.onProgress(url, downloaded, length, usedTime);
        }
    };

    private void install(String filePath) {
        try {
            File apkFile = new File(filePath);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(
                        getBaseContext()
                        , Constant.FILE_PATH
                        , apkFile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }
            startActivity(intent);
            finish();
        } catch (Exception e) {
            //showToast("安装失败,请重试");
        }
    }



}
